package com.todod.common.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.FileCopyUtils;

import com.todod.exception.DownLoadException;

public class Download {

	private static Logger log = LoggerFactory.getLogger(Download.class);

	/**
	 * 生成随机文件名
	 * 
	 * @param fileName
	 * @return
	 */
	public static String generateFileName(String fileName) {
		DateFormat format = new SimpleDateFormat("yyMMddHHmmss");
		String formatDate = format.format(new Date());

		int random = new Random().nextInt(10000);

		int position = fileName.lastIndexOf(".");
		String extension = fileName.substring(position);

		return formatDate + random + extension;
	}

	/**
	 * 把文件推到前台浏览器
	 */
	public static void download(HttpServletRequest request, HttpServletResponse response, InputStream is,
			String originalName) {

		OutputStream out = null;
		try {

			setResponseHeader(request, response, originalName);
			out = response.getOutputStream();
			FileCopyUtils.copy(is, out);
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 
	 * @Title: download
	 * @Description: 根据路径下载
	 * @author：gsh
	 * @date: 2019年4月30日
	 * @param request
	 * @param response
	 * @param abstractPath
	 * @param originalName
	 * @throws DownLoadException
	 * @return void
	 */
	public static void download(HttpServletRequest request, HttpServletResponse response, String abstractPath,
			String originalName) throws DownLoadException {

		OutputStream out = null;
		InputStream is = null;
		try {

			is = new FileInputStream(abstractPath);

			setResponseHeader(request, response, originalName);
			out = response.getOutputStream();
			FileCopyUtils.copy(is, out);
			out.flush();
		} catch (Exception e) {
			log.error("下载异常", e);
			e.printStackTrace();
			throw new DownLoadException();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 
	 * @Title: setResponseHeader
	 * @Description: 设置响应头
	 * @author：gsh
	 * @date: 2019年4月30日
	 * @param request
	 * @param response
	 * @param originalName
	 * @return void
	 */
	public static void setResponseHeader(HttpServletRequest request, HttpServletResponse response,
			String originalName) {

		try {
			originalName = originalName.replaceAll("\\s", "+"); // 空间名有空格,ff下载会自动截图

			String agent = request.getHeader("USER-AGENT");
			String downloadName;
			if (StringUtils.contains(agent, "MSIE") || StringUtils.contains(agent, "Trident")) // IE
			{
				downloadName = URLEncoder.encode(originalName, "UTF-8");
			} else if (StringUtils.contains(agent, "Mozilla")) // 其它
			{
				downloadName = new String(originalName.getBytes("UTF-8"), "ISO-8859-1");
			} else {
				downloadName = URLEncoder.encode(originalName, "UTF-8");
			}

			response.setHeader("Location", downloadName);
			response.setHeader("Content-Disposition", "attachment; filename=" + downloadName); // attachment下载;disposition在线浏览
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}